#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple Network Check for SMS Receiver HTTP Service
"""

import socket
import urllib.request
import urllib.error

def get_local_ip():
    """Get local IP address"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(("8.8.8.8", 80))
            return s.getsockname()[0]
    except:
        return "Unable to determine"

def check_port_open(host, port):
    """Check if a port is open"""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(3)
            result = s.connect_ex((host, port))
            return result == 0
    except:
        return False

def test_http_request(host, port):
    """Test HTTP request"""
    url = f"http://{host}:{port}/?code=123456"
    try:
        request = urllib.request.Request(url)
        with urllib.request.urlopen(request, timeout=5) as response:
            status_code = response.getcode()
            response_text = response.read().decode('utf-8')
            return True, status_code, response_text
    except Exception as e:
        return False, 0, str(e)

def main():
    print("SMS Receiver HTTP Service Network Check")
    print("=" * 50)
    
    # Get local IP
    local_ip = get_local_ip()
    print(f"Local IP Address: {local_ip}")
    
    port = 8889  # HTTP port (now the main and only port)
    
    print(f"\nTesting HTTP service on port {port} (HTTP only):")
    print("-" * 30)
    
    # Test localhost
    print(f"\n1. Testing localhost:")
    localhost_open = check_port_open("localhost", port)
    print(f"   Port open: {'YES' if localhost_open else 'NO'}")
    
    if localhost_open:
        success, status, response = test_http_request("localhost", port)
        if success:
            print(f"   HTTP test: SUCCESS (Status: {status})")
        else:
            print(f"   HTTP test: FAILED ({response})")
    
    # Test 127.0.0.1
    print(f"\n2. Testing 127.0.0.1:")
    loopback_open = check_port_open("127.0.0.1", port)
    print(f"   Port open: {'YES' if loopback_open else 'NO'}")
    
    # Test local IP
    if local_ip != "Unable to determine":
        print(f"\n3. Testing local IP ({local_ip}):")
        ip_open = check_port_open(local_ip, port)
        print(f"   Port open: {'YES' if ip_open else 'NO'}")
        
        if ip_open:
            success, status, response = test_http_request(local_ip, port)
            if success:
                print(f"   HTTP test: SUCCESS (Status: {status})")
            else:
                print(f"   HTTP test: FAILED ({response})")
    else:
        print(f"\n3. Testing local IP: SKIPPED (IP not available)")
        ip_open = False
    
    # Summary and recommendations
    print(f"\nSUMMARY:")
    print("-" * 20)
    
    if not localhost_open:
        print("- SMS Receiver app is NOT running")
        print("  ACTION: Start the SMS Receiver application")
    elif localhost_open and not ip_open:
        print("- Service only accessible via localhost")
        print("  ACTION: Check firewall settings")
        print("  ACTION: Run app as administrator")
        print("  ACTION: See HTTP_ACCESS_GUIDE.md for details")
    elif localhost_open and ip_open:
        print("- Service is accessible via both localhost and IP")
        print("  STATUS: Everything looks good!")
    
    print(f"\nTest URLs:")
    print(f"- http://localhost:{port}/?code=123456")
    if local_ip != "Unable to determine":
        print(f"- http://{local_ip}:{port}/?code=123456")

if __name__ == "__main__":
    main()
